﻿

CREATE PROCEDURE [dbo].[GenDepartamenteParam]
	@CodUnitate smallint,
	@An smallint,
	@Luna smallint
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @cate int
	DECLARE @perioada int
	SELECT @cate = COUNT(*) FROM [DepartamenteParametrii] WHERE CodUnitate=@CodUnitate AND Luna=@Luna and An=@An
	IF @cate<>0
		return
	SELECT TOP 1 @cate = COUNT(*),@perioada = An*100+Luna FROM [DepartamenteParametrii] WHERE CodUnitate=@CodUnitate
	AND An*100+Luna<=@An*100+@Luna
	GROUP BY An*100+Luna
	ORDER BY An*100+Luna
	IF @cate<>0
	BEGIN
		INSERT INTO [DepartamenteParametrii]
			   ([IDDepartament]
			   ,[Luna]
			   ,[An]
			   ,[NrPaturi]
			   ,[Suprafata]
			   ,[CodUnitate])
		 SELECT IDDepartament,@Luna, @An,NrPaturi,Suprafata,@CodUnitate  FROM [DepartamenteParametrii] WHERE CodUnitate=@CodUnitate
			AND An*100+Luna=@perioada
	END
	ELSE
		BEGIN
			INSERT INTO [DepartamenteParametrii]
				   ([IDDepartament]
				   ,[Luna]
				   ,[An]
				   ,[NrPaturi]
				   ,[Suprafata]
				   ,[CodUnitate])
			 SELECT IDDepartament,@Luna, @An,CAST(COALESCE([NumericField],0) as int) NrParuri,COALESCE(Suprafata,0) Suprafata,@CodUnitate  FROM [Departamente] WHERE CodUnitate=@CodUnitate
		END
	
		
END